#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
// 自定义写
int my_write(int fd,char* str);
// 自定义读
int my_read(int fd,char* str);
/* 自定义协议结构体 */
typedef struct{
	int bytes;
	char data[512];
}my_protocol;
int main(int argc,char* argv[])
{
	if(argc < 3)
	{
		printf("incorrect parameter\n");
		return 1;
	}
	int client_fd = socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in client_attr;
	memset(&client_attr,0,sizeof(client_attr));
	client_attr.sin_family = AF_INET;
	// 主机字节序转换成网络字节序
	client_attr.sin_port = htons((short)atoi(argv[2]));
	inet_pton(AF_INET,argv[1],&client_attr.sin_addr.s_addr);
	// client_attr.sin_addr.s_addr = 
	if(-1 == connect(client_fd,(struct sockaddr*)&client_attr,sizeof(client_attr)))
	{
		perror("connect ");
		return 1;
	}
	char res[512];
	while(1)
	{
		memset(res,'\0',sizeof(res));
		scanf("%s",res);
		if(-1 == my_write(client_fd,res))
		{
			perror("write");
			break;
		}
		if(my_read(client_fd,res) <= 0)
		{
			perror("read");
			break;
		}
		printf("res = %s",res);
	}
	close(client_fd);
	return 0;
}
int my_write(int fd,char* str)
{
	my_protocol p = {0};
	memset(&p.data,'\0',sizeof(p.data));
	strcpy(p.data,str);
	p.bytes = strlen(p.data);
	if(write(fd,&p,sizeof(p)) < 0)
	{
		return -1;
	}
	return 0;
}
int my_read(int fd,char* str)
{
	my_protocol p = {0};
	memset(&p.data,'\0',sizeof(p.data));
	int read_len = 0;
	read_len = read(fd,&p,sizeof(p));
	if(p.bytes != strlen(p.data) && read_len != 0)
	{
		return -1;
	}
	strcpy(str,p.data);
	return read_len;
}
